import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Category } from './category.entity';
import { CasbinRoleService } from '../casbin/casbin-role.service';

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(Category)
    private categoryRepository: Repository<Category>,
    private readonly casbinRoleService: CasbinRoleService,
  ) {}

  async findAll(): Promise<Category[]> {
    const categories = await this.categoryRepository.find();
    // 如果没有分类数据，创建一些默认分类
    if (categories.length === 0) {
      console.log('数据库中没有分类，创建默认分类');
      const defaultCategories = [
        { name: '默认分类', parentId: 0 },
        { name: '技术文章', parentId: 0 },
        { name: '生活随笔', parentId: 0 }
      ];
      
      for (const cat of defaultCategories) {
        const category = this.categoryRepository.create(cat);
        await this.categoryRepository.save(category);
      }
      
      return await this.categoryRepository.find();
    }
    return categories;
  }

  async findOne(id: number): Promise<Category | null> {
    return await this.categoryRepository.findOne({ where: { id } });
  }

  async create(categoryData: Partial<Category>): Promise<Category> {
    const category = this.categoryRepository.create(categoryData);
    return await this.categoryRepository.save(category);
  }

  async update(id: number, categoryData: Partial<Category>): Promise<Category | null> {
    await this.categoryRepository.update(id, categoryData);
    return await this.categoryRepository.findOne({ where: { id } });
  }

  async remove(id: number): Promise<void> {
    await this.categoryRepository.delete(id);
  }

  /**
   * 获取分类树形结构
   */
  async getTree(): Promise<Category[]> {
    const categories = await this.findAll();
    return this.buildTree(categories);
  }

  /**
   * 获取用户有权限的分类
   * @param user 用户信息
   */
  async getAuthorizedCategories(user: any): Promise<Category[]> {
    console.log('获取授权分类，用户信息:', user);
    const categories = await this.findAll();
    console.log('所有分类:', categories);
    
    // 获取用户的角色
    const userRoles = user?.roles || [];
    console.log('用户角色:', userRoles);
    
    // 如果用户是管理员，返回所有分类
    if (userRoles.includes('admin') || userRoles.includes('super')) {
      console.log('用户是管理员，返回所有分类');
      return this.buildTree(categories);
    }
    
    // 检查用户每个角色的权限
    const authorizedCategoryIds = new Set<number>();
    
    for (const roleName of userRoles) {
      // TODO: 需要实现获取角色分类权限的逻辑
      // 这里暂时跳过，因为我们还没有实现完整的分类权限功能
    }
    
    // 如果没有任何权限设置，默认返回所有分类
    if (authorizedCategoryIds.size === 0) {
      console.log('没有特定权限设置，返回所有分类');
      return this.buildTree(categories);
    }
    
    // 过滤出用户有权限的分类
    const authorizedCategories = categories.filter(category => 
      authorizedCategoryIds.has(category.id)
    );
    
    return this.buildTree(authorizedCategories);
  }

  /**
   * 构建树形结构
   * @param categories 分类列表
   * @param parentId 父级ID
   */
  private buildTree(categories: Category[], parentId = 0): Category[] {
    return categories
      .filter(category => category.parentId === parentId)
      .map(category => ({
        ...category,
        children: this.buildTree(categories, category.id),
      }));
  }
}